package com.zy.rpc.consumer.processor;

import com.zy.rpc.common.discovery.DiscoveryService;
import com.zy.rpc.consumer.annotation.RpcAutowired;
import com.zy.rpc.consumer.config.RpcClientProperties;
import com.zy.rpc.consumer.proxy.ClientStubProxyFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;


/**
 * @author zy
 * @date 2023/5/7 10:34
 */
@Component
@ConditionalOnMissingBean(RpcClientProcessor.class)
public class RpcClientProcessor implements BeanPostProcessor  {


    @Autowired
    private  DiscoveryService discoveryService;
    @Autowired
    private  RpcClientProperties rpcClientProperties;


    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> clazz = bean.getClass();
        ReflectionUtils.doWithFields(clazz, field -> {
            RpcAutowired annotation = AnnotationUtils.findAnnotation(field, RpcAutowired.class);
            if (annotation != null) {
                field.setAccessible(true);
                ReflectionUtils.setField(field, bean, ClientStubProxyFactory.getProxy(field.getType(), discoveryService, rpcClientProperties));
            }
        });
        return bean;
    }
}

